package BFS_DFS;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class BFS_迷宫最短路径 {
    static int n;
    static int m;
    static int[][] maze;
    static boolean[][] vis;
    static int[][] dir=new int[][]{
            {-1, 0}, {1, 0}, {0, -1}, {0, 1}
    };

    static class Node{
        int x,y,steps;//x,y,当前步数
        Node(int x,int y,int steps){
            this.x=x;
            this.y=y;
            this.steps=steps;
        }
    }

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        n=sc.nextInt();
        m=sc.nextInt();
        maze=new int[n][m];
        vis=new boolean[n][m];
        int startX=-1,startY=-1;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                maze[i][j]=sc.nextInt();
                if(maze[i][j]==0&&startX==-1&&startY==-1){
                    startX=i;
                    startY=j;
                }
            }
        }
        sc.close();
        if(startX==-1||startY==-1){
            System.out.println("no");
            return;
        }
        int minStep=bfs(startX,startY);
        if(minStep==Integer.MAX_VALUE){
            System.out.println("no");
        }else{
            System.out.println(minStep);
        }
    }

    static int bfs(int x,int y){
        Queue<Node> queue=new LinkedList<>();
        queue.offer(new Node(x,y,0));//入队
        vis[x][y]=true;//标记已入队
        while (!queue.isEmpty()){
            Node top=queue.poll();
            if(maze[top.x][top.y]==2){
                return top.steps;
            }
            for (int i = 0; i < 4; i++) {
                int tx=top.x+dir[i][0];
                int ty=top.y+dir[i][1];
                if(inMaze(tx,ty)&&!vis[tx][ty]&&(maze[tx][ty]==0||maze[tx][ty]==2)){
                    //在迷宫内且未访问且可通行
                    queue.offer(new Node(tx,ty,top.steps+1));//创建新结点入队
                    vis[tx][ty]=true;//标记已访问
                }
            }
        }
        return Integer.MAX_VALUE;//没找到，返回最大值
    }

    static boolean inMaze(int x,int y){
        return (0<=x&&x<n&&0<=y&&y<m);
    }
}
